package com.wzj.yygh.sms.controller;


import com.wzj.yygh.common.result.R;
import com.wzj.yygh.sms.service.SmsService;
import com.wzj.yygh.sms.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags = "短信接口")
@RestController
@RequestMapping("/front/sms")
@Slf4j
public class FrontSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送手机验证码
    @ApiOperation("发送短信")
    @PostMapping("send/{phone}")
    public R sendCode(@PathVariable String phone) {
        // 生成验证码，
        String code = RandomUtil.getFourBitRandom();
        log.info("验证码为:{}",code);
        //调用service方法，通过整合短信服务进行发送
        boolean isSend = smsService.send(phone,code);
        //生成验证码放到redis里面，设置有效时间
        if(isSend) {
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok().message("发送短信成功");
        } else {
            return R.error().message("发送短信失败");
        }
    }
}
